package cn.kevinkun.LeanCloud;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.Component;
import com.google.appinventor.components.runtime.ComponentContainer;
import com.google.appinventor.components.runtime.EventDispatcher;

import android.app.Activity;

@DesignerComponent(version = 20241014, category = ComponentCategory.EXTENSION, description = "http://www.kevinkun.cn/leancloud.html", iconName = "aiwebres/leancloud.svg", nonVisible = true)
@SimpleObject(external = true)
@UsesPermissions(permissionNames = "android.permission.INTERNET")
public class LeanCaptcha extends AndroidNonvisibleComponent implements Component {

	String url = "";
	String appid = "";
	String appkey = "";
	String token = "";
	String apiversion = "1.1";
	Map<String, String> headers = new HashMap<String, String>();
	private final Activity activity;

	public LeanCaptcha(ComponentContainer container) {
		super(container.$form());
		activity = container.$context();
	}

	@SimpleFunction(description = "")
	public void Init(String restApiUrl, String appId, String appKey) {
		url = restApiUrl;
		appid = appId;
		appkey = appKey;

		headers.clear();
		headers.put("X-LC-Id", appid);
		headers.put("X-LC-Key", appkey);
		headers.put("Content-Type", "application/json");
	}

	@SimpleFunction(description = "")
	public void requestCaptcha() {
		String realUrl = url + "/" + apiversion + "/requestCaptcha";

		HttpUtils.doHttpReqeust("GET", realUrl, headers, null, new HttpUtils.Callback() {

			@Override
			public void onError(String error) {
				activity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						OnError(error);
					}
				});
			}

			@Override
			public void onSuccess(String result) {
				activity.runOnUiThread(new Runnable() {
					public void run() {
						JSONObject object;
						try {
							object = new JSONObject(result);
							token = object.getString("captcha_token");
							final String captcha_url = object.getString("captcha_url");
							GotCaptcha(captcha_url);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});
			}
		});

	}

	@SimpleFunction(description = "")
	public void verifyCaptcha(String captchaCode) {

		try {
			String realUrl = url + "/" + apiversion + "/verifyCaptcha";

			JSONObject object = new JSONObject();
			object.put("captcha_code", captchaCode);
			object.put("captcha_token", token);

			String body = object.toString();
			HttpUtils.doHttpReqeust("POST", realUrl, headers, body.getBytes(), new HttpUtils.Callback() {

				@Override
				public void onError(String error) {
					activity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							OnError(error);
						}
					});
				}

				@Override
				public void onSuccess(String result) {
					activity.runOnUiThread(new Runnable() {
						public void run() {
							JSONObject objResponse;
							try {
								objResponse = new JSONObject(result);
								final String validate_token = objResponse.getString("validate_token");
								VerifiedCaptcha(validate_token, objResponse.toString());
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								onError("decoding error: " + result);
							}

						}
					});
				}
			});
		} catch (JSONException e) {
			// TODO Auto-generated catch block

		}

	}

	@SimpleEvent
	public void GotCaptcha(String captcha) {
		EventDispatcher.dispatchEvent(this, "GotCaptcha", captcha);
	}

	@SimpleEvent
	public void VerifiedCaptcha(String validateToken, String result) {
		EventDispatcher.dispatchEvent(this, "VerifiedCaptcha", validateToken, result);
	}

	@SimpleEvent
	public void OnError(String error) {
		EventDispatcher.dispatchEvent(this, "OnError", error);
	}

}
